import {
  wxRequest
} from '../../../utils/server.js';
const _wxRequest = new wxRequest();
const app = getApp()

Page({
  data: {
    imgUrl: app.globalData.imgUrl,
    cartShade: false,
    imgUrl: app.globalData.imgUrl,
    hasNextPage: false,
    uploadUrl: wx.getStorageSync('uploadUrl'),
    keyword: '',
    goodlist: [],
    cartList: [],
    totalPice: 0,
    pageNo:1, 
    catId: '',
    purchase: '',
    sortType: '',
    purchaseList: [{
      id: '',
      text: "全部"
    }, {
      id: 1,
      text: "仅限平台采购"
    }, {
      id: '0',
      text: "商城商品"
    }],
  },

  onLoad: function() {
    this.getlist().then(() => {
      this.getShopCartList();
    });
  },

  onShow: function () {
    if (wx.getStorageSync('settleBack')) {
      this.getlist().then(() => {
        this.getShopCartList();
        wx.setStorageSync('settleBack', false)
      });
    }
  },
  //获取购物车列表
  getShopCartList() {
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + '/odr/protected/shoppingCart/list',
      method: 'POST',
      data: {}
    }, (res) => {
      let cartList = res.list
    let goodlist = this.data.goodlist;
      goodlist.map(item => {
        cartList.map(cartListItem => {
          if(item.id === cartListItem.gdsId) {
            item.qty = cartListItem.qty
          }
        })
      })
      this.setData({
        goodlist,
        cartList
      })
      this.totalPrice();
    })
  },

  //查看购物车详情
  viewCartDetail: function() { 
    this.setData({
      cartShade: !this.data.cartShade
    })
  },

  //显示购物车列表，防止关闭
  showViewCartDetail: function() {
    this.setData({
      cartShade: true
    })
  },


  //加入购物车
  addCart: function(e) {
    let checkItem = e.currentTarget.dataset.item;
    let id = e.currentTarget.dataset.id;
    let cartList = this.data.cartList || []
    let qty = e.detail.x? 1: e.detail; //加入购入车数量
    var goodlist = this.data.goodlist
    cartList.map(item => {
      if (item.id == id) {
        item.qty = qty
      }
    })
    //更新购物车列表,如果已经存在更新数量，如果不存在新增
    var newArr = JSON.stringify(cartList)
    if (newArr.indexOf(checkItem.id) < 0) {
      checkItem.qty = 1
      checkItem.gdsId = checkItem.id
      cartList.push(checkItem)
      delete checkItem.id;
      _wxRequest.wxTonkenAjax({
        url: app.globalData.apiUrl + '/odr/protected/shoppingCart/add',
        method: 'post',
        data: checkItem
      }, (res) => {
        wx.showToast({
          title: '加入购物车成功',
        })
      })
    } else {
      cartList.map(item => {
        if (item.gdsId == id) {
          item.qty = qty
        }
      })
      //过滤掉小于1
      cartList.map(item => { 
        _wxRequest.wxTonkenAjax({
          url: app.globalData.apiUrl + '/odr/protected/shoppingCart/add',
          method: 'post',
          data: item
        }, (res) => {
        })
      })
      cartList = cartList.filter(item => item.qty > 0);
    }
 
    this.setData({
      goodlist,
      cartList
    })
    wx.setStorageSync('goodsOdrList', cartList);
    this.totalPrice();
  },


  //计算总金额
  totalPrice: function() {
    var cartList = this.data.cartList;
    var totalPice = 0
    cartList.map(item => {
      totalPice += item.price * item.qty
    })
    totalPice = totalPice.toFixed(2)
    this.setData({
      totalPice
    })
  },



  //清空购物车
  delAllCartList: function() {
    var that = this
    wx.showModal({
      title: '提示',
      confirmText: '确定',
      cancelText: '取消',
      content: '确定清空购物车',
      success: function(res) {
        if (res.confirm) {
          wx.showToast({
            icon: 'none',
            title: '删除成功',
          })
          that.removeCartList();
          var goodlist = that.data.goodlist
          goodlist.map(item => {
            item.qty = 0
          })

          that.setData({
            cartList: [],
            goodlist,
            cartShade: false
          })
          that.totalPrice()
        }
      } 
    }) 
  },

  removeCartList() {
    if(this.data.cartList.length > 0) {
      let cartList = this.data.cartList;
      cartList.map(item => {
        _wxRequest.wxTonkenAjax({
          url: app.globalData.apiUrl + '/odr/protected/shoppingCart/delete?carId='+parseInt(item.id),
          method: 'POST',
          data:{}
        }, (res) => {
          
        })
      })
    }
  },

  //提交订单
  onClickButton: function () {

    wx.showLoading({
      title: '加载中',
    })  


    var cartList = this.data.cartList;    
    if (cartList.length > 0) {
      wx.setStorageSync('goodsOdrList', cartList)
      wx.setStorageSync('odrTotalPrice', this.data.totalPice)
      wx.navigateTo({
        url: '/pages/settle/index',
      })
    } else {
      wx.showToast({
        title: '请选择采购商品',
      })
    }
  },


  //商品请求
  getlist: function() {
    return new Promise((resolve, reject) => {
      _wxRequest.wxTonkenAjax({
        url: app.globalData.apiUrl + '/gds/protected/gdsMgt/findPurchaseList' ,
        method: 'POST',
        data:{
          keyword: this.data.keyword,
          pageNo:this.data.pageNo,
          catId: this.data.catId,
          braId: this.data.braId,
          purchase:this.data.purchase
        }
      }, (res) => {
        let list = res.list;
        if (this.data.pageNo !== 1) {
          list = this.data.goodlist.concat(list);
        }
  
        this.setData({
          goodlist: list,
          pageNo: res.page.pageNo,
          hasNextPage: res.page.hasNextPage,
        }, () => {
          resolve();
        });
      })
    })
    
  },



  //下拉刷新
  onPullDownRefresh: function() {
    this.refreshData();
    wx.stopPullDownRefresh()
  },

  refreshData: function() {
    this.setData({
      pageNo: 1
    })
    this.getlist();
  },

  //触底时，加载更多
  onReachBottom: function() {
    if (this.data.hasNextPage) {
      this.setData({
        pageNo: this.data.pageNo + 1
      });
      this.getlist();
    }
  },

  //搜索关键词
  seachInputConfirm: function(e) {
    this.setData({
      pageNo: 1,
      keyword: e.detail.value
    })
    this.getlist();
  },

  seachBtn: function () {
    this.setData({
      pageNo: 1,
      keyword: this.data.keyword
    })
    this.getlist();
  },


  seachInputVal: function(e) {
    var inputval = e.detail.value;
    console.log(e)
    this.setData({
      keyword: inputval
    })
  },

  //清空
  clearInput: function() {
    this.setData({
      keyword: ''
    })
    this.getlist();
  },


  //加入购物车
  addCate: function() {
    var params = {
      gdsId: this.data.id,
      qty: 1,
    }
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + '/odr/protected/shoppingCart/add',
      method: 'post',
      data: params
    }, (res) => {
      wx.showToast({
        title: '加入购物车成功',
      })
    })
  },

  //订单列表
  goOrderList:function(){
    wx.navigateTo({
      url:'/pages/order/index'
    })
  },

 



  // 分类
  handleCat: function (e) {
    var that = this;
    var sortType = e.currentTarget.dataset.type;
    this.setData({
      catflag: true,
      sortType
    })

    that.getCat()
  },

  getCat: function () {
    _wxRequest.wxAjax({
      url: app.globalData.apiUrl + "/gds/goods/findGoodsCat",
      method: 'POST',
      data: {}
    }, (res) => {
      console.log(res, '分类')
      this.setData({
        catlist: res.list
      })
      this.getbrand()
    })
  },
  //选择分类
  handleCatItem: function (e) {
    var code = e.currentTarget.dataset.code;
    console.log(code,'code')
    this.setData({
      catId: Number(code),
      catflag: false,
    })
    this.getlist()
  },

  //品牌
  getbrand: function () {
    _wxRequest.wxAjax({
      url: app.globalData.apiUrl + "/gds/brand/find",
      method: 'POST',
      data: {
        catId: this.data.catId
      }
    }, (res) => {
      console.log(res, '品牌')
      this.setData({
        brandList: res.list
      })
    })
  },


  toGoodsDetail(e) {
    var id = e.currentTarget.dataset.id
    console.log(e)
    wx.navigateTo({
      url: '/pages/good/detail/index?id=' + id,
    })
  },



  //********************筛选更多********************
  popupRight: function () {
    this.setData({
      showPopup: true
    })
    this.getCat()
  },

  popupCancel: function () {
    this.setData({
      showPopup: false
    })
  },

  popupConfirm: function () {
    this.getlist();
    this.popupCancel();
  },

  //选择状态
  checkpurchase: function (e) {
    var purchase = e.currentTarget.dataset.id || ''
    console.log(purchase, 'status')
    this.setData({
      purchase
    })
  },

  //选择分类
  handleCatItem: function (e) {
    var code = e.currentTarget.dataset.id;
    this.setData({
      catId: code,
    })
    this.getbrand()
  },

  handlebrand: function (e) {
    var code = e.currentTarget.dataset.id;
    this.setData({
      braId: code,
    })
  },
  //********************筛选更多end********************


})